package com.crm.service.crm.transfer.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.crm.model.common.dtos.PageResponseResult;
import com.crm.model.common.dtos.ResponseResult;
import com.crm.model.common.enums.AppHttpCodeEnum;
import com.crm.model.crm.businessOpportunities.pojo.CustomInfo;
import com.crm.model.crm.clue.pojos.Clue;
import com.crm.model.crm.transfer.redeploy.dtos.RedeployDto;
import com.crm.model.crm.transfer.redeploy.dtos.RedeployHandleDto;
import com.crm.model.crm.transfer.redeploy.pojos.Redeploy;
import com.crm.model.crm.transfer.redeploy.vo.RedeployVO;
import com.crm.model.system.department.pojos.Department;
import com.crm.model.system.department.vo.DepartmentVO;
import com.crm.model.system.pojo.User;
import com.crm.model.system.vos.UserVO;
import com.crm.service.crm.businessOpportunities.mapper.CustomInfoMapper;
import com.crm.service.crm.clue.mapper.CueMapper;
import com.crm.service.crm.transfer.mapper.RedeployMapper;
import com.crm.service.crm.transfer.service.RedeployService;
import com.crm.service.system.department.mapper.DepartmentMapper;
import com.crm.service.system.mapper.UserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class RedeployServiceImpl extends ServiceImpl<RedeployMapper, Redeploy>  implements RedeployService {
    @Autowired
    private RedeployMapper redeployMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private DepartmentMapper departmentMapper;

    @Autowired
    private CueMapper clueMapper;

    @Autowired
    private CustomInfoMapper customInfoMapper;

    /**
     * 转派管理的条件分页查询
     *
     * @param dto
     * @return
     */
    public ResponseResult findPhoneOrNameOrTime(RedeployDto dto) {
        //1.参数校验
        dto.checkParam();
        //2.构造查询条件
        IPage<Redeploy> page = new Page<>(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<Redeploy> wrapper = new LambdaQueryWrapper<>();
        //查询手机号码
        if (dto.getPhone() != null) {
            wrapper.like(Redeploy::getPhone, dto.getPhone());
        }
        //查询用户名称
        if (StringUtils.isNotBlank(dto.getName())) {
            wrapper.like(Redeploy::getUserName, dto.getName());
        }
        //查询时间范围
        if (dto.getCreatedTime() != null && dto.getEndTime() != null) {
            LocalDate created = dto.getCreatedTime();
            LocalDate end = dto.getEndTime();
            LocalDateTime createdTime = created.atStartOfDay();
            LocalDateTime endTime = end.atStartOfDay();
            wrapper.between(Redeploy::getCreatedTime,createdTime,endTime);
        }
        //分页查询
        page = page(page, wrapper);
        ResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        result.setData(page.getRecords());
        //返回分页数据
        return result;
    }

    /**
     * 转派管理处理回显
     *
     * @param id
     * @return
     */
    public ResponseResult updateRedeploy(Integer id) {
        //1.校验参数
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //2.根据用户id查询转派信息
        Redeploy redeploy = redeployMapper.selectById(id);
        if (redeploy == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //3.准备查询条件
        RedeployVO redeployVO = new RedeployVO();
        BeanUtils.copyProperties(redeploy, redeployVO);
        LambdaQueryWrapper<User> userWrapper = new LambdaQueryWrapper<>();
        //3.1准备容器
        List<DepartmentVO> departmentVOS = new ArrayList<>();
        //调用方法获取部门信息
        departmentVOS = getDepartmentVOS(userWrapper, departmentVOS);
        //存入部门集合到redeployVo
        redeployVO.setDepartment(departmentVOS);

        //返回转派详情
        return ResponseResult.okResult(redeployVO);
    }

    /**
     * 获取部门信息
     *
     * @param userWrapper
     * @param departmentVOS
     * @return
     */
    private List<DepartmentVO> getDepartmentVOS(LambdaQueryWrapper<User> userWrapper, List<DepartmentVO> departmentVOS) {
        //获取部门信息
        List<Department> departments = departmentMapper.selectList(null);
        //查询部门信息
        String departmentName = null;
        List<UserVO> userVOS = null;
        for (Department department : departments) {
            //创建部门VO对象并装入信息
            DepartmentVO departmentVO = new DepartmentVO();
            BeanUtils.copyProperties(department, departmentVO);
            //获取部门名称
            departmentName = departmentVO.getDepartmentName();
            //调用方法获取用户信息
            userVOS = getUserVOS(userWrapper, departmentName);
            //存入用户集合departmentVO
            departmentVO.setUsers(userVOS);
            //添加部门信息到部门集合
            departmentVOS.add(departmentVO);
        }
        return departmentVOS;
    }

    /**
     * 获取用户信息
     *
     * @param userWrapper
     * @param departmentName
     * @return
     */
    private List<UserVO> getUserVOS(LambdaQueryWrapper<User> userWrapper, String departmentName) {
        //根据部门名称查询用户
        userWrapper.eq(User::getDepartment, departmentName);
        //根据条件获取用户信息
        List<User> users = userMapper.selectList(userWrapper);
        List<UserVO> userVOS = new ArrayList<>();
        //查询用户信息
        for (User user : users) {
            //创建用户vo对象并存入信息
            UserVO userVO = new UserVO();
            BeanUtils.copyProperties(user, userVO);
            //添加用户信息到user集合
            userVOS.add(userVO);
        }
        return userVOS;
    }

    /**
     * 转派处理修改
     * @return
     */
    public ResponseResult updateRedeploy(RedeployHandleDto dto) {
        //1.参数校验
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        ResponseResult error = ParameterValidation(dto);
        if (error != null) {
            return error;
        }
        //2.修改线索分配人员
        //根据减员用户id查询线索编号
        LambdaQueryWrapper<Clue> clueWrapper = new LambdaQueryWrapper<>();
        clueWrapper.eq(Clue::getOwnerId,dto.getUserId());
        List<Clue> clues = clueMapper.selectList(clueWrapper);
        //根据线索编号修改拥有人和归属部门
        for (Clue clue : clues) {
            //获取线索编号
            String cueIdName = clue.getCueIdName();
            clue.setOwnerId(dto.getUserId().longValue());
            clue.setCueBelongerName(dto.getUser());
            //进行修改
            clueWrapper.eq(Clue::getCueIdName,cueIdName);
            clueMapper.update(clue,clueWrapper);
        }
        //3.修改商机(客户)分配人员
        //根据减员用户名称获取客户id
        LambdaQueryWrapper<CustomInfo> customWrapper = new LambdaQueryWrapper<>();
        customWrapper.eq(CustomInfo::getRevert,dto.getReduction());
        List<CustomInfo> customInfos = customInfoMapper.selectList(customWrapper);
        //根据客户id修改归属人
        for (CustomInfo customInfo : customInfos) {
            //获取客户id
            Integer id = customInfo.getId();
            customInfo.setRevert(dto.getUser());

            //进行修改
            customInfoMapper.updateById(customInfo);
        }
        return null;
    }

    /**
     * 转派处理确认参数校验
     * @param dto
     * @return
     */
    private ResponseResult ParameterValidation(RedeployHandleDto dto) {

        //线索数量判断
        if (dto.getClueDetails() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        if (dto.getClueDetails() != null && dto.getClueDetails() > 3) {
            return ResponseResult.errorResult(AppHttpCodeEnum.CLUE_ERROR);
        }
        //商机数量判断
        if (dto.getBusinessDetails() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        if (dto.getClueDetails() != null && dto.getBusinessDetails() > 3) {
            return ResponseResult.errorResult(AppHttpCodeEnum.BUSINESS_ERROR);
        }
        //分配部门校验
        if (StringUtils.isBlank(dto.getDepartment())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //分配人员校验
        if (StringUtils.isBlank(dto.getUser())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        return null;
    }
}
